package com.touchfired.common.exception;

import com.touchfired.common.http.response.Msg;
import com.touchfired.common.http.response.MsgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Msg<Object> defaultExceptionHandler(Exception e){
        Msg<Object> result;

        if (e instanceof HttpMessageNotReadableException) {
            result = MsgUtil.error(ErrorCode.ERROR_400.getCode(), ErrorCode.ERROR_400.getDesc(), null);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            result = MsgUtil.error(ErrorCode.ERROR_400.getCode(), ErrorCode.ERROR_400.getDesc(), null);
        } else if (e instanceof NoHandlerFoundException) {
            result = MsgUtil.error(ErrorCode.ERROR_404.getCode(), ErrorCode.ERROR_404.getDesc(), null);
        } else if (e instanceof ServiceException) {
            ServiceException exception = (ServiceException) e;
            result = MsgUtil.error(exception.getCode(), exception.getDesc(), null);
        } else {
            result = MsgUtil.error(ErrorCode.ERROR_500.getCode(), ErrorCode.ERROR_500.getDesc(), null);
            e.printStackTrace();
        }

        return result;
    }
}
